<html lang="zh" class="loading in-dev-mode">
<head>
<title>星盟优品货盘系统</title>
  <meta charset="utf8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no, viewport-fit=cover">
  <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
  <script type="text/javascript" src="https://www.layuicdn.com/layui/layui.js"></script>
  <script src="https://cdn.nikm.cn/js/jquery.js"></script>
<script src="https://cdn.nikm.cn/js/jr-qrcode.js"></script>
  <style type="text/css">
    .layui-table-cell {
        height: auto !important;
    }
    .layui-table img {
        max-width: 300px !important;
    }
    .info .info-amout{
        font-size: 16px;
        color: #ff5722;
        margin-right: 10px;
    }

    .info {
        font-size: 12px;
        line-height: 20px;
        margin: 0px 0 0px;
    }
   
    .info i {
        font-style: normal;
        font-size: 10px;
        color:#666;
        margin-right: 3px;
    }
    .info .info-commision {
        margin-left: 10px;
    }

    .layui-table-page>div {
        height: 38px !important;
    }
    .layui-laypage a, .layui-laypage span {
        font-size: 14px !important;
    }
    .layui-laypage a, .layui-laypage span {
        height: 38px !important;
    }

    .layui-table-page .layui-laypage a, .layui-table-page .layui-laypage span {
        height: 38px !important;
        line-height: 38px !important;
    }
    .layui-elem-quote {
        border-left: 5px solid #FAFAFA;
        padding: 10px;
    }
    .layui-carousel-ind {
        display: none;
    }
  </style>
</head>
<body>
<div class="layui-fluid">
    <div style="margin-top:5px"></div>

    <form class="layui-form layui-form-pane" style="margin-top:20px">
        <div class="layui-row">
            <div class="layui-col-xs12">
                <input type="text" name="date" id="goods-keyword" placeholder="查找更多商品或同款商品多个价格" autocomplete="off" class="layui-input" value="">
            </div>
        </div>

        <div class="layui-row" style="margin-top:15px">
            <div class="layui-col-xs8">
                <button type="button" style="height:37px; line-height:37px;width: 100%;" class="layui-btn layui-btn-danger search-goods">搜索产品</button>
            </div>
            <div class="layui-col-xs1"><p>&nbsp;</p></div>
            <div class="layui-col-xs3">
                <button type="button" style="height:37px; line-height:37px;width: 100%;" class="layui-btn layui-btn-primary reset-serach-goods">重置列表</button>
            </div>
        </div>
    </form>
    <div style="margin-top:20px"></div>
    <table id="goods-list-table" lay-filter="goods-list-table"  ></table>
    <div style="margin-top:20px"></div>
    <div id="qrcode"></div>
</div>
</body>
<script type="text/html" id="goods-action-tool-bar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="copyId">复制ID</a>
    <!-- <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="setCommission">设置佣金</a> -->
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="copyGoods">推广文案</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="qr">推广信息</a>
</script>
<script type="text/javascript">
    var $;
    var form;
    var table;
    var layer;
    var carousel;
    var tag = "48BgfVXfxEm"
    var mustTag = true;

    layui.use(['layer', 'table', 'form', 'carousel'], function () {
        $ = layui.jquery
        , layer = layui.layer
        , table = layui.table
        , form = layui.form 
        , carousel = layui.carousel
        
        form.render()

        // 轮播图
        carousel.render({
            elem: '#test1'
            ,width: '100%' //设置容器宽度
            , height: '100px'
            ,arrow: 'none' //始终显示箭头
            //,anim: 'updown' //切换动画方式
        });
        
        table.render({
        elem: '#goods-list-table'
        , url: 'http://110.42.251.192/item/getall'
        , skin: 'line'
        , page: {
            layout: ["prev", "page", "next", 'count'],
        }
        , limit: 10
        , limits: [10, 20, 30, 50]
        , where: {
            tag: tag
        }
        , cols: [[ //表头
            , {
                field: 'Cover', title: '图片', width: 160, templet: function (item) {
                    if (item.Cover == "") {
                        return "-"
                    }
                    return '<div style="padding:10px 0px"><img class="showImg" src="' + item.Cover
                        + '" style="width:130px;height:130px;"></div>'
                }
            }
            , { field: 'Title', title: '商品信息', templet: function(item) {
                return "<div style='margin-left:-10px'><p style='white-space:normal;word-break:break-word;line-height:20px'>" + item.Title + "</p>"
                + "<p class='info' style='margin-top:5px;'><span class='info-amout'><i>预估佣金</i>¥"+Math.round((item.Price / 100) * (item.Commission / 1000000) * 100) / 100+"</span></p>"
                + "<p class='info' style='margin-top:-2px;margin-bottom:10px'><span class='info-price'><i>售价</i>¥" + item.Price / 100 + "</span>"
                + "<span class='info-commision'><i>佣金率</i>" + item.Commission / 10000 + "%</span></p>"
                + "<button class='layui-btn layui-btn-primary layui-btn-sm copy-product-id' data-id='"+item.ProductId+"'>复制ID</button>"
                + "<button class='layui-btn layui-btn-danger layui-btn-sm see-product-qr' style='margin-left:15px' data-id='"+item.ProductId+"'>添加到橱窗</button></div>"
            }}
        ]]
        });

        layui.table.on('sort(goods-list-table)', function (obj) {
            console.log(obj)
            var where = obj.config.where;
            where["sortField"] = obj.field
            where["sortType"] = obj.type

            table.reload('goods-list-table', {
            page: {
                curr: obj.config.page.curr //重新从第 1 页开始
            }
            ,where: where
            });
        })

        $(document).on("click", ".search-goods", function() {
            var keyword = $("#goods-keyword").val()
            if (keyword.trim() == "") {
                layer.msg("请输入商品关键词")
                return  
            }
    

            table.reload('goods-list-table', {
                page: {
                    curr: 1 //重新从第 1 页开始
                    , layout: ["prev", "page", "next", 'count'],
                }
                ,where: {
                    key: keyword,
                    tag: tag
                }
            });
        })

        $(document).on("click", ".reset-serach-goods", function() {
            table.reload('goods-list-table', {
            page: {
                curr: 1 //重新从第 1 页开始
                ,layout: ["prev", "page", "next", 'count'],
            }
            ,where: {
                tag: tag
            }
            });

        })

        $(document).on("click", ".copy-product-id", function() {
            var dummy = document.createElement('textarea');
                document.body.appendChild(dummy);
                dummy.value = $(this).attr("data-id");
                dummy.select(); // 选择对象
                document.execCommand('copy'); // 执行浏览器复制命令
                document.body.removeChild(dummy);
                layer.msg('复制成功', { time: 1000 });          
        })
        $(document).on("click", ".see-product-qr", function() {
            var id = $(this).attr("data-id")
            var base64_img = jrQrcode.getQrBase64("https://liteapp.weixin.qq.com/q/ABMNbs?shopId=" + $(this).attr("data-id"));
            var img = "<div style='padding:10px 20px 20px'>"
                + "<img src='"+base64_img+"' style='width:200px;height:200px'>"
                + "<p style='width:100%;text-align:center;color:red;margin-top:5px'>长按并识别二维码图片添加橱窗</p></div>";

            // 更新view
            setTimeout(() => {
               getAjax("http://110.42.251.192/item/up/view?id="+id, function(res) {
                    var rsp = JSON.parse(res);
                    if (!rsp.success) {
                        console.log("更新view失败：" + id)
                    }
                }) 
            }, 1000);
            
            img_show = layer.open({
                type: 1,
                area: [240, 320],
                shadeClose: true, //点击遮罩关闭
                title: '添加到橱窗',
                content: img    
            });
     
        })
    })

    function getAjax(url, cb) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    cb(xhr.responseText);
                } else {
                    cb('error');
                }
            }
        };
        xhr.send();
    }


    function timestampToTime(timestamp) {
        var date = new Date(timestamp );//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = date.getDate() + ' ';
        h = date.getHours() + ':';
        m = date.getMinutes() + ':';
        s = date.getSeconds();
        return Y+M+D+h+m+s;
    }

    /**
     * 复制图片，接受 data: URI 和 http[s] 的图片地址
     * @param url
     * @returns {Promise<unknown>}
     */
    function image2blob (url) {
        return new Promise(resolve => {
            // 如果是 data 开头的就使用 DataURI 的解析
            if (url.indexOf('data:') === 0) {
                return resolve(new ClipboardItem({ 'image/png': dataURItoBlob(url) }))
            }
            const img = new Image
            const c = document.createElement('canvas')
            const ctx = c.getContext('2d')

            img.onload = function () {
                c.width = this.naturalWidth
                c.height = this.naturalHeight
                ctx.drawImage(this, 0, 0)
                c.toBlob(blob => resolve(new ClipboardItem({ 'image/png': blob })), 'image/png', 1)
            }

            img.crossOrigin = ''
            img.src = url
        })

    }

    /**
     * 将 data: 开头的 dataURI base64 图片转为 blob
     * @param dataURI
     * @returns {Blob}
     */
    function dataURItoBlob (dataURI) {
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] // mime类型
        var byteString = atob(dataURI.split(',')[1]) //base64 解码
        var arrayBuffer = new ArrayBuffer(byteString.length) //创建缓冲数组
        var intArray = new Uint8Array(arrayBuffer) //创建视图

        for (var i = 0; i < byteString.length; i++) {
            intArray[i] = byteString.charCodeAt(i)
        }
        return new Blob([intArray], { type: mimeString })
    }

    /**
     * 复制图片
     * @param url
     * @returns {Promise<unknown>}
     */
    function copyImage (url) {
        return new Promise((resolve, reject) => {
            image2blob(url).then(data => {
                navigator.clipboard.write([data]).then(resolve, reject)
            })
        })
    }

</script>
</html>